//
//  DXYHomeViewController.m
//  Piece
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "DXYHomeViewController.h"
#import "ZHNetworkHandler.h"
#import "XZHHomeModel.h"
#import "XZHHomeCollectionViewCell.h"
#import "Masonry.h"
#import "XZHHomeTableView.h"
#import "XZHSearchViewController.h"
#import "AAPullToRefresh.h"
#import "XZHHomeListViewController.h"
#import "XZHHomeDetailViewController.h"
#import "XZHHomeListDetailViewController.h"
#import "XZHHomeNoteViewController.h"
#import "FeHourGlass.h"
#import "JZShareCustom.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "UIImageView+WebCache.h"
#import "ZHArchiverTools.h"

@interface DXYHomeViewController () <UICollectionViewDataSource, UICollectionViewDelegate, HomeTableViewCellDelegate>
 
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayOut;
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) NSInteger praisenum;
@property (nonatomic, strong) UILabel *likeLabel;

@property (strong, nonatomic) FeHourGlass *hourGlass;
@end

@implementation DXYHomeViewController {
    BOOL isLike;
}

- (void)dealloc {
    self.collectionView.delegate = nil;
    self.collectionView.dataSource = nil;
}

- (void)loadView {
    [super loadView];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavigationBarButtonWithPicture:@"plant" Picture:@"play"];
    UILabel *label = [[UILabel alloc]init];
    label.frame = CGRectMake(150, -10, 55, 30);
    label.text = @"PIECE";
    label.font = [UIFont fontWithName:@"Helvetica" size:20];
    label.textColor = [UIColor colorWithRed:0.29 green:0.36 blue:0.42 alpha:1.00];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    self.view.backgroundColor = [UIColor colorWithRed:1.00 green:1.00 blue:1.00 alpha:1.00];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    [self setUpTags];
    [self setUpCollectionView];
    
    [self setUpLeftRefreshView];
    [self setUpRightReloadView];
    [self getDataByUrl];
    
}

#pragma mark 创建右拉刷新视图
- (void)setUpLeftRefreshView {
    __weak DXYHomeViewController *weakSelf = self;
    AAPullToRefresh *pullToRefreshLeft = [self.collectionView addPullToRefreshPosition:AAPullToRefreshPositionLeft actionHandler:^(AAPullToRefresh *left) {
        [left performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
        [weakSelf getDataByUrl];
        [weakSelf.collectionView setContentOffset:CGPointMake(0, 0) animated:NO];
        weakSelf.flowLayOut.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 49 - 64 -40);
        weakSelf.flowLayOut.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }];
    pullToRefreshLeft.threshold = 60;
    //小圈的颜色:
    pullToRefreshLeft.borderColor = [UIColor colorWithRed:0.54 green:0.69 blue:0.84 alpha:1.00];
    pullToRefreshLeft.borderWidth = 4;
    pullToRefreshLeft.imageIcon = [UIImage new];
}
#pragma mark 创建左拉加载视图
- (void)setUpRightReloadView {
    __weak DXYHomeViewController *weakSelf = self;
    AAPullToRefresh *pullToRefreshRight = [self.collectionView addPullToRefreshPosition:AAPullToRefreshPositionRight actionHandler:^(AAPullToRefresh *right) {
        [right performSelector:@selector(stopIndicatorAnimation) withObject:nil afterDelay:1];
        XZHHomeListViewController *listVC = [[XZHHomeListViewController alloc] init];
        [weakSelf.navigationController pushViewController:listVC animated:YES];
    
        weakSelf.flowLayOut.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 49 - 64 -40);
        weakSelf.flowLayOut.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }];
    pullToRefreshRight.threshold = 60;
    //小圈的颜色:
    pullToRefreshRight.borderColor = [UIColor colorWithRed:0.54 green:0.69 blue:0.84 alpha:1.00];
    pullToRefreshRight.borderWidth = 4;
    pullToRefreshRight.imageIcon = [UIImage new];
}

#pragma mark 创建标签
- (void)setUpTags {
    UIButton *btn_note = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn_note setBackgroundImage:[UIImage imageNamed:@"diary_normal"] forState:UIControlStateNormal];
    [self.view addSubview:btn_note];
    [btn_note makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(10);
        make.bottom.equalTo(self.view.bottom).offset(-30);
        make.height.equalTo(20);
        make.width.equalTo(50);
    }];
    
    UIButton *btn_more = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn_more setBackgroundImage:[UIImage imageNamed:@"share_image"] forState:UIControlStateNormal];
    [self.view addSubview:btn_more];
    [btn_more makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.right).offset(-10);
        make.top.equalTo(btn_note).offset(-14);
        make.width.equalTo(40);
        make.height.equalTo(40);
    }];
    

    UIButton *btn_heart = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn_heart setBackgroundImage:[UIImage imageNamed:@"like_normal"] forState:UIControlStateNormal];
    [self.view addSubview:btn_heart];
    [btn_heart makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(btn_more.left).offset(-40);
        make.top.equalTo(btn_more).offset(1);
        make.width.equalTo(40);
        make.height.equalTo(40);
    }];
    [btn_heart setTag:1200];
    
    self.likeLabel = [[UILabel alloc] init];
    self.likeLabel.textColor = [UIColor colorWithRed:0.74 green:0.74 blue:0.74 alpha:1.00];
    self.likeLabel.font = [UIFont systemFontOfSize:11];
    [self.view addSubview:_likeLabel];
    UIButton *button = (UIButton *)[self.view viewWithTag:1200];
    [self.likeLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(button.right);
        make.bottom.equalTo(button.bottom);
        make.height.equalTo(button);
        make.width.equalTo(40);
    }];
    [self.likeLabel setTag:1201];
}

#pragma mark 喜欢的代理方法
- (void)changLikeImageView:(XZHHomeModel *)model {
    static const CGFloat scaleMultiple = 2.0;
    NSInteger likeCount =[[self.likeLabel text] integerValue];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"like_%@",model.hpcontent_id]]){
        
        [(UIButton *)[self.view viewWithTag:1200] setImage:[UIImage imageNamed:@"like_selected"] forState:UIControlStateNormal];
        self.likeLabel.text = [NSString stringWithFormat:@"%ld", likeCount + 1];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:[NSString stringWithFormat:@"like_%@",model.hpcontent_id]];
        
        UIButton *button = (UIButton *)[self.view viewWithTag:1200];
        [UIView animateWithDuration:0.1 delay:0 usingSpringWithDamping:1.0 initialSpringVelocity:0.1 options:UIViewAnimationOptionCurveEaseIn animations:^{
            
            button.transform = CGAffineTransformMakeScale(scaleMultiple, scaleMultiple);
        } completion:^(BOOL finished) {
            
            [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.3 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                
                button.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                
            }];
        }];
        
    } else {
        [(UIButton *)[self.view viewWithTag:1200] setImage:[UIImage imageNamed:@"like_normal"] forState:UIControlStateNormal];
        self.likeLabel.text = [NSString stringWithFormat:@"%ld", likeCount - 1];
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:[NSString stringWithFormat:@"like_%@",model.hpcontent_id]];
    }
}

#pragma mark 分享的代理方法
-(void)shareHP:(XZHHomeModel *)model; {
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:[NSString stringWithFormat:@"%@ [%@]",model.hp_content, model.hp_author]
                                         images:model.hp_img_url
                                            url:[NSURL URLWithString:model.web_url]
                                          title:@"PIECE"
                                           type:SSDKContentTypeAuto];
        //调用自定义分享
        [JZShareCustom shareWithContent:shareParams Url:model.web_url  Title:nil Type:nil HomeModel:model MovieModel:nil];
//    }
}

#pragma mark 小记的代理方法
- (void)editNote:(XZHHomeModel *)model{
    XZHHomeNoteViewController *noteVC = [[XZHHomeNoteViewController alloc] init];
    noteVC.model = model;
    [self.navigationController pushViewController:noteVC animated:NO];
}

#pragma mark 滑动的代理方法
- (void)swipeTableView {
    XZHSearchViewController *searchVC = [[XZHSearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:NO];
}

#pragma mark 创建集合视图
- (void)setUpCollectionView {
    self.flowLayOut = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayOut.itemSize = CGSizeMake(ScreenWidth, ScreenHeight - 49 - 64);
    self.flowLayOut.minimumInteritemSpacing = 0;
    self.flowLayOut.minimumLineSpacing = 0;
    self.flowLayOut.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    self.flowLayOut.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 49 - 64) collectionViewLayout:self.flowLayOut];
    self.collectionView.backgroundColor =[UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    [self.collectionView resignFirstResponder];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    [self.collectionView registerClass:[XZHHomeCollectionViewCell class] forCellWithReuseIdentifier:@"homeCollectionViewCell"];
}

#pragma mark 集合视图的代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    XZHHomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homeCollectionViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.tableView.delegate = self;
    self.model = [self.dataSource objectAtIndex:indexPath.item];
    cell.model = self.model;
    cell.homeVC = self;
    return cell;
}

#pragma mark 数据请求
- (void)getDataByUrl {
    //加载动画
    _hourGlass = [[FeHourGlass alloc] initWithView:self.collectionView];
    [self.view addSubview:_hourGlass];
    [_hourGlass showWhileExecutingBlock:^{
        [self myTask];
    } completion:^{
        
    }];
    [ZHNetworkHandler getDataByURLString:@"http://v3.wufazhuce.com:8000/api/hp/more/0" WithBodyString:nil WithHeaderDic:nil WithResponse:0 WithSuccess:^(id result) {
        NSDictionary *dic = (NSDictionary *)result;
        //数据缓存
        [ZHArchiverTools archiverObject:dic ByKey:@"homeCache" WithPath:@"home.plist"];
        [self analyseDataByDictionary:dic];
//        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        //移除加载动画
        [_hourGlass removeFromSuperview];
    } WithFailure:^(NSError *error) {
        NSDictionary *dic = (NSDictionary *)[ZHArchiverTools unarchiverObjectByKey:@"homeCache" WithPath:@"home.plist"];
        if (dic == nil) {
            
        }
        else
        {
            [self analyseDataByDictionary:dic];
            [_hourGlass removeFromSuperview];
        }

    }];
}

#pragma mark 解析数据
- (void)analyseDataByDictionary:(NSDictionary *)dic {
    self.dataSource = [NSMutableArray array];
    for (NSDictionary *dict in [dic objectForKey:@"data"]) {
        XZHHomeModel *model = [[XZHHomeModel alloc] initWithDic:dict];
        [self.dataSource addObject:model];
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            if ([[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"like_%@",model.hpcontent_id]]) {
                [(UIButton *)[self.view viewWithTag:1200] setImage:[UIImage imageNamed:@"like_selected"] forState:UIControlStateNormal];
                self.likeLabel.text = [NSString stringWithFormat:@"%ld", [[self.dataSource objectAtIndex:0] praisenum] + 1];
            } else {
                self.likeLabel.text = [NSString stringWithFormat:@"%ld", [[self.dataSource objectAtIndex:0] praisenum]];
                [(UIButton *)[self.view viewWithTag:1200] setImage:[UIImage imageNamed:@"like_normal"] forState:UIControlStateNormal];
            }
        });
    }
    [self.collectionView reloadData];
}

#pragma mark 滚动停止
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger index = (scrollView.contentOffset.x - ScreenWidth) /ScreenWidth + 1;
    XZHHomeModel *model = [self.dataSource objectAtIndex:index];
    self.likeLabel.text = [NSString stringWithFormat:@"%ld", model.praisenum];
    [(UIButton *)[self.view viewWithTag:1200] setImage:[UIImage imageNamed:@"like_normal"] forState:UIControlStateNormal];
    
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"like_%@",model.hpcontent_id]]) {
        [(UIButton *)[self.view viewWithTag:1200] setImage:[UIImage imageNamed:@"like_selected"] forState:UIControlStateNormal];
        self.likeLabel.text = [NSString stringWithFormat:@"%ld", model.praisenum+1];
    } else {
        self.likeLabel.text = [NSString stringWithFormat:@"%ld", model.praisenum];
        [(UIButton *)[self.view viewWithTag:1200] setImage:[UIImage imageNamed:@"like_normal"] forState:UIControlStateNormal];
    }
}

#pragma mark 视图将要出现
- (void)viewWillAppear:(BOOL)animated
{

    //[self.view bringSubviewToFront:self.playView];

    //将播放页带到最前面
   // [self.view bringSubviewToFront:self.playView];
    [[self.navigationController.navigationBar viewWithTag:1260] setHidden:NO];
    [[self.navigationController.navigationBar viewWithTag:1260] setUserInteractionEnabled:YES];
    [[self.navigationController.navigationBar viewWithTag:1261] setHidden:NO];
    [[self.navigationController.navigationBar viewWithTag:1261] setUserInteractionEnabled:YES];
    //加载动画

    [_hourGlass showWhileExecutingBlock:^{
        //[self myTask];
    } completion:^{
        
    }];
}
- (void)viewWillDisappear:(BOOL)animated {
//    [self createNavigationBarButtonWithPicture:@"" Picture:@""];
    
}
#pragma mark 加载任务
- (void)myTask
{
    // Do something usefull in here instead of sleeping ...
    sleep(6);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
